package org.witsoft.localmq.impl;

import org.witsoft.localmq.FileManager;
import org.witsoft.localmq.FileWriter;
import org.witsoft.localmq.model.Message;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Synchronized;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: MqFileWriteImpl
 * @Description:
 * @Author: Colin
 * @Date: 2020/12/26 11:13 AM
 * @Version 1.0
 **/
@RequiredArgsConstructor
public class FileWriteImpl implements FileWriter {

    @NonNull
    private FileManager fileManager;

    @Override
    @Synchronized
    public void write(List<Message> messages) throws IOException{
        if(messages.isEmpty()){
            return;
        }
        Map<Integer, List<Message>> groups = messages.stream().collect(Collectors.groupingBy(Message::getSegment));
        for (int segmentId : groups.keySet()) {
            File dataFile = fileManager.getSegmentDataFile(segmentId);
            File indexFile = fileManager.getSegmentIndexFile(segmentId);
            try(RandomAccessFile dataRaf = new RandomAccessFile(dataFile, "rws")){
                try(RandomAccessFile idxRaf = new RandomAccessFile(indexFile, "rws")){
                    for (Message message : groups.get(segmentId)) {
                        long pointer = dataRaf.length();
                        // 写入数据
                        byte[] data = message.getData();
                        dataRaf.seek(pointer);
                        dataRaf.writeInt(data.length);
                        dataRaf.write(data);
                        // 写入索引
                        idxRaf.seek(message.getPosition() * 12);
                        idxRaf.writeInt(message.getPosition());
                        idxRaf.writeLong(pointer);
                    }
                }
            }
        }
    }
}
